<template>
  <div class="w-[100%] h-[100%] unselectable">
    <clickMap
      ref="clickMapRef"
      :key="markey"
      :markerArr="data"
      @markerClick="markerClick"
      :bgImg="bgImg"
      @init="onInit"
      :editAble="false"
      :isShowPopup="false"
    >
    </clickMap>
  </div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import clickMap from "@/components/clickMap/show-marker.vue";
import { useDataDashboardThemeStoreHook } from "@/store/modules/data-dashboard-theme";
import {
  getBuildingInfo,
  getDrawingInfo,
  getMonitorInfo,
  getFacilityInfo,
  getDeviceInfo,
  getDeviceBaseInfo
} from "@/api/screen";
import { projectpoint } from "@/api/screen/screenmune";
import { cloneDeep } from "@pureadmin/utils";
import { ICON_TYPE_Map } from "@/constant/index";
import facilityInformationPopup from "./facilityInformationPopup.vue";
import monitorInfoPopup from "./monitorInfoPopup.vue";
import deviceInfoPopup from "./deviceInfoPopup.vue";
import { addDialog } from "@/components/ReDialog";
import { emitter } from "@/utils/mitt";
import { isEqual } from "@pureadmin/utils";
const useDataDashboardThemeStore = useDataDashboardThemeStoreHook();
const markey = ref(0);
const clickMapRef = ref(null);
const data = ref([]);
const markersa = ref([]);
const bgImg = ref("");
onMounted(() => {
  emitter.on("alarmEventsProject", mesage);
  // window.popupClick = function(params) {
  //   console.log(params);

  // }

  // getMarkImg();
});

onBeforeUnmount(() => {
  emitter.off("alarmEventsProject", mesage);
  window.popupClick = null;
});

watch(
  () => useDataDashboardThemeStore.GET_SETTING("dataDashboardIsHidden"),
  (newValue, oldValue) => {
    getMarkImg(useDataDashboardThemeStore.GET_SETTING("showverviewalrm"));
  }
);
watch(
  () => useDataDashboardThemeStore.GET_SETTING("showverviewalrm"),
  (newValue, oldValue) => {
    console.log(newValue,'点击内容');
    
    if (clickMapRef.value) {
      clickMapRef.value.clearMarkers();
    }
    getMarkImg(newValue);
  }
);

// 监听图纸标点、点位、楼层id改变事件
watch(
  () => useDataDashboardThemeStore.drawmapid,
  (newValue, oldValue) => {
    getMarkImg(2);
  }
);
watch(
  () => useDataDashboardThemeStore.GET_SETTING("projectInfo"),
  (newValue, oldValue) => {
    // bgImg.value =
    //   useDataDashboardThemeStore.GET_SETTING("projectInfo").projectPlan;
    getMarker();
  },
  { immediate: true, deep: true }
);

async function getMarker() {
  getMarkImg(useDataDashboardThemeStore.GET_SETTING("showverviewalrm"));
}

const markerClick = (item: any) => {
  let itemInfo = item[0].markerItem;
  if (itemInfo?.type == "building") {
    console.log(itemInfo?.type, "res1.result");
    useDataDashboardThemeStore.CHANGE_SETTING({
      key: "dataDashboardIsHidden",
      value: 2
    });
    // 点击图纸标点后获取建筑及初始化图纸信息，默认选中第一张图纸
    getBuildingInfo({ buildingId: itemInfo?.buildingId }).then(res => {
      useDataDashboardThemeStore.building.buildingInfo = res.result;
      if (res.result?.drawingInfo && res.result?.drawingInfo.length > 0) {
        let defaultDrawing =
          res.result?.drawingInfo.find((item: any) => item.isDefault == 1) ??
          res.result?.drawingInfo[0];
        getDrawingInfo({
          buildingId: res.result?.buildingInfo?.buildingId,
          drawingId: defaultDrawing?.drawingId
        }).then(res1 => {
          useDataDashboardThemeStore.building.drawingInfo = res1.result;
          useDataDashboardThemeStore.building.checkedDrawingId =
            defaultDrawing?.drawingId;
        });
      }
    });
  } else if (itemInfo?.type == "monitor") {
    getMonitorInfo({ monitorId: itemInfo?.monitorId }).then(res => {
      res.code == 200 &&
        addDialog({
          title: res.result?.monitorName,
          width: "800px",
          draggable: true,
          hideFooter: true,
          fullscreen: false,
          fullscreenIcon: true,
          closeOnClickModal: false,
          props: {
            monitorUrl: res.result?.url,
            playDuration: res.result?.playDuration
          },
          contentRenderer: () => h(monitorInfoPopup)
        });
    });
  } else if (itemInfo?.type == "facilit") {
    getFacilityInfo({ facilitId: itemInfo?.facilitId }).then(res => {
      res.code == 200 &&
        addDialog({
          title: res.result?.facilitName,
          width: "800px",
          draggable: true,
          hideFooter: true,
          fullscreen: false,
          fullscreenIcon: true,
          closeOnClickModal: false,
          props: {
            formInline: res.result
          },
          contentRenderer: () => h(facilityInformationPopup)
        });
    });
  } else if (itemInfo?.type == "device") {
    getDeviceBaseInfo({ deviceId: itemInfo?.deviceId }).then(res => {
      res.code == 200 &&
        addDialog({
          title: res.result?.deviceName,
          width: "1100px",
          draggable: true,
          fullscreen: false,
          fullscreenIcon: true,
          closeOnClickModal: false,
          props: {
            isLoading: false,
            newFormInline: res.result,
            id: itemInfo?.deviceId
          },
          hideFooter: true,
          contentRenderer: () => h(deviceInfoPopup)
        });
    });
  }
};

const onInit = () => {
  getMarkImg(useDataDashboardThemeStore.GET_SETTING("showverviewalrm"));
};
function arraysAreEqual(arr1, arr2) {
  if (arr1.length !== arr2.length) {
    return false;
  }

  for (let i = 0; i < arr1.length; i++) {
    if (!isEqual(arr1[i], arr2[i])) {
      return false;
    }
  }

  return true;
}
function getMarkImg(type = 1) {
  markersa.value = [];
  let newbgImg = "";
  if (useDataDashboardThemeStore.GET_SETTING("dataDashboardIsHidden") == 1) {
    projectpoint().then(res => {
      if (res.code == 200) {
        newbgImg =
          useDataDashboardThemeStore.GET_SETTING("projectInfo").projectPlan;
        res.result.building.forEach((item: any) => {
          if (item.drawingPoint.lat !== "" && item.drawingPoint.lng !== "") {
            item.type = "building";
            item.drawingPoint.info = cloneDeep(item);
            let marker = {
              markerItem: cloneDeep(item),
              lat: item.drawingPoint.lat,
              lng: item.drawingPoint.lng,
              iconSvg: null,
              iconType: "building",
              color: item.alarmNum == 0 ? "blue" : "red",
              popupOption: {
                showPopup: true,
                buildingName: item.buildingName,
                alarmCount: item.alarmNum
              }
            };
            if( useDataDashboardThemeStore.GET_SETTING("dataDashboardIsHidden")==1){
               if(type==1){
                markersa.value.push(marker);
               }else{
                if(item.alarmNum>0){
                  markersa.value.push(marker);
                }
               }
            }else{
              markersa.value.push(marker);
            }
            
          }
        });
        res.result.device.forEach((item: any) => {
          if (item.drawingPoint.lat !== "" && item.drawingPoint.lng !== "") {
            item.type = "device";
            item.drawingPoint.info = cloneDeep(item);
            let marker = {
              markerItem: cloneDeep(item),
              lat: item.drawingPoint.lat,
              lng: item.drawingPoint.lng,
              iconSvg: item.deviceIcon,
              iconType: "device",
              color: item.commStatus == 1 ? "blue" : "red"
            };
            if (
              useDataDashboardThemeStore.GET_SETTING("dataDashboardIsHidden") ==
              1
            ) {
              if (type == 1) {
                markersa.value.push(marker);
              } else {
                if (item.commStatus !== 1) {
                  markersa.value.push(marker);
                }
              }
            } else {
              markersa.value.push(marker);
            }
          }
        });
        res.result.facilit.forEach((item: any) => {
          if (item.drawingPoint.lat !== "" && item.drawingPoint.lng !== "") {
            item.type = "facilit";
            let marker = {
              markerItem: cloneDeep(item),
              lat: item.drawingPoint.lat,
              lng: item.drawingPoint.lng,
              iconSvg: item.facilitIcon,
              iconType: "facilit",
              color:
                istimes(item.expireDate, item.scrapDate) == 1 ? "blue" : "red"
            };
            if (
              useDataDashboardThemeStore.GET_SETTING("dataDashboardIsHidden") ==
              1
            ) {
              if (
                istimes(item.expireDate, item.scrapDate) == type ||
                type == 1
              ) {
                markersa.value.push(marker);
              }
            } else {
              markersa.value.push(marker);
            }
          }
        });
        res.result.monitor.forEach((item: any) => {
          if (item.drawingPoint.lat !== "" && item.drawingPoint.lng !== "") {
            item.type = "monitor";
            item.drawingPoint.info = cloneDeep(item);
            let marker = {
              markerItem: cloneDeep(item),
              lat: item.drawingPoint.lat,
              lng: item.drawingPoint.lng,
              iconSvg: null,
              iconType: "monitor",
              color: "blue"
            };
            markersa.value.push(marker);
          }
        });
        nextTick(() => {
          if (
            bgImg.value !== newbgImg ||
            !arraysAreEqual(markersa.value, data.value) ||
            type == 2
          ) {
            bgImg.value = newbgImg;
            data.value = markersa.value;
            clickMapRef.value.changeImgLayer(bgImg.value).then(res => {
              clickMapRef.value.setMarkers(data.value);
            });
          }
        });
      }
    });
  } else {
    let arrdatya = [];
    let newbgImg =
      useDataDashboardThemeStore.GET_SETTING("building")?.drawingInfo
        ?.drawingInfo.img;
    useDataDashboardThemeStore
      .GET_SETTING("building")
      ?.drawingInfo?.device.forEach((item: any) => {
        if (item.drawingPoint.lat !== "" && item.drawingPoint.lng !== "") {
          // item.type = 'device'
          // item.drawingPoint.info = cloneDeep(item);
          // arrdatya.push(item.drawingPoint);
          item.type = "device";
          item.drawingPoint.info = cloneDeep(item);
          let marker = {
            markerItem: cloneDeep(item),
            lat: item.drawingPoint.lat,
            lng: item.drawingPoint.lng,
            iconSvg: item.deviceIcon,
            iconType: "device",
            color: item.commStatus == 1 ? "blue" : "red"
          };
          arrdatya.push(marker);
        }
      });
    useDataDashboardThemeStore
      .GET_SETTING("building")
      ?.drawingInfo?.facilits.forEach((item: any) => {
        if (item.drawingPoint.lat !== "" && item.drawingPoint.lng !== "") {
          // item.type = 'facilits'
          // item.drawingPoint.info = cloneDeep(item);
          // arrdatya.push(item.drawingPoint);
          item.type = "facilit";
          let marker = {
            markerItem: cloneDeep(item),
            lat: item.drawingPoint.lat,
            lng: item.drawingPoint.lng,
            iconSvg: item.facilitIcon,
            iconType: "facilit",
            color:
              istimes(item.expireDate, item.scrapDate) == 1 ? "blue" : "red"
          };
          arrdatya.push(marker);
        }
      });
    useDataDashboardThemeStore
      .GET_SETTING("building")
      ?.drawingInfo?.monitor.forEach((item: any) => {
        if (item.drawingPoint.lat !== "" && item.drawingPoint.lng !== "") {
          // item.type = 'monitor'
          // item.drawingPoint.info = cloneDeep(item);
          // arrdatya.push(item.drawingPoint);
          item.type = "monitor";
          item.drawingPoint.info = cloneDeep(item);
          let marker = {
            markerItem: cloneDeep(item),
            lat: item.drawingPoint.lat,
            lng: item.drawingPoint.lng,
            iconSvg: null,
            iconType: "monitor",
            color: "blue"
          };
          arrdatya.push(marker);
        }
      });
    nextTick(() => {
      if (
        bgImg.value !== newbgImg ||
        JSON.stringify(arrdatya) !== JSON.stringify(data.value)
      ) {
        bgImg.value = newbgImg;
        data.value = arrdatya;
        console.log(data.value, "数据111");
        clickMapRef.value.changeImgLayer(bgImg.value).then(res => {
          clickMapRef.value.setMarkers(data.value);
        });
      }
    });
  }
}
function mesage() {
  getMarkImg(useDataDashboardThemeStore.GET_SETTING("showverviewalrm"));
}
// 获取时间是否已过期
function istimes(oldtime, oldtime2) {
  //1 已过期 2 未过期
  let nows = new Date();
  let timeis = nows.getTime() - new Date(oldtime).getTime();
  let timeis1 = nows.getTime() - new Date(oldtime2).getTime();
  if (timeis > 0 || timeis1 > 0) {
    return 2;
  } else {
    return 1;
  }
}
</script>
<style lang="scss" scoped>
.unselectable {
  -webkit-user-select: none;
  /* Safari 3.1+ */
  -moz-user-select: none;
  /* Firefox 2+ */
  -ms-user-select: none;
  /* IE 10+ */
  user-select: none;
  /* 标准语法 */
}
</style>
